﻿#include "ServerMonitor.h"
#include "global.h"
#include <QBuffer>

QMutex g_DebugMutex;
QWaitCondition g_DebugCondition;
ServerMonitor::ServerMonitor(QObject *parent): QObject(parent)
{

}

void ServerMonitor::slot_init()
{
    //********************初始化ws***************************//
    pWebsocket = new QWebSocket();
    connect(pWebsocket, SIGNAL(disconnected()), this, SLOT(slot_wsdisconnected()), Qt::AutoConnection);
    connect(pWebsocket, SIGNAL(connected()), this, SLOT(slot_wsconnected()), Qt::AutoConnection);
    connect(pWebsocket, SIGNAL(binaryMessageReceived(const QByteArray &)), SLOT(slot_binaryMessageReceived(const QByteArray &)) , Qt::AutoConnection);
    connect(pWebsocket,SIGNAL(textMessageReceived(const QString &)),this,SLOT(slot_textMessageReceived(const QString &)));
    connect(pWebsocket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(slot_error(QAbstractSocket::SocketError)));

    conTimer = new QTimer(this);
    connect(conTimer,SIGNAL(timeout()),this,SLOT(slot_timerout()));
    conTimer->setInterval(2000);

    conTimer->start();
}

void ServerMonitor::slot_timerout()
{
    if(!isServerConnected){
        pWebsocket->open(QUrl(wsurl));
    }
}

void ServerMonitor::slot_wsconnected()
{
    conTimer->stop();
    isServerConnected = true;

    mylog<<"ws connected!!!";
}

void ServerMonitor::slot_wsdisconnected()
{
    isServerConnected = false;
    conTimer->start();
    mylog<<"ws disconnected!!!";
}

void ServerMonitor::slot_binaryMessageReceived(const QByteArray &)
{

}

void ServerMonitor::slot_textMessageReceived(const QString &message)
{
    QJsonParseError jsonError;
    QJsonObject json;
    json = QJsonDocument::fromJson(message.toUtf8(),&jsonError).object();
    if(json.isEmpty() == false && jsonError.error == QJsonParseError::NoError)  //  转换成功并且收到的数据非空
    {
        mylog<<"recv cmd from server:"<<json;
        emit sig_ServerCommandReady(json);              //  发送给命令队列，解析出命令类型后，加入队列---ServerCommandManager接收
    }
    else
    {
        mylog<<jsonError.error;
    }
}

void ServerMonitor::slot_error(QAbstractSocket::SocketError er)
{
    mylog<<er;
}

void ServerMonitor::slot_sendDataToServer(QJsonObject data)
{
    if(!isServerConnected)  return;
    QJsonDocument doc(data); // 创建一个QJsonDocument对象，包含QJsonObject
    QString jsonString = doc.toJson(QJsonDocument::Compact); // 转换
    pWebsocket->sendTextMessage(jsonString);
}

void ServerMonitor::slot_imgResultToServer(QImage image)
{
    if(!isServerConnected)  return;
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    // 将 QImage 保存到 QBuffer 中，使用 PNG 格式
    if (!image.save(&buffer, "PNG")) {
        qWarning() << "Failed to save image to buffer.";
        return;
    }
    mylog<<byteArray.size();
    // 发送字节数组作为二进制消息
    pWebsocket->sendBinaryMessage(byteArray);
}
